<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Category;
use Overtrue\Pinyin\Pinyin;
use services\QCloudSmsService;
use think\Db;
use think\db\Query;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\model\relation\OneToOne;

/**
 * 预约住房管理
 *
 * @icon fa fa-circle-o
 */
class Reservation extends Backend
{
    /**
     * Reservation模型对象
     * @var \app\admin\model\Reservation
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Reservation;

    }

    public function import()
    {
        parent::import();
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model->where($where)
                ->order($sort, $order)
                ->paginate($limit)
                ->each(function ($item) {
                    $item['user_type'] = $item->user->hospitalization_count > 0 ? '老病人' : '新病人';
                });

            return json(["total" => $list->total(), "rows" => $list->items()]);
        }
        return $this->view->fetch();
    }

    /**
     * Description:
     *
     * @param null $ids
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @return mixed
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if ($params['status'] == 1) {
                        if ($row['status'] == 1) {
                            exception(__('当前预约已经通过！'));
                        }
                        if ($row['stay_date'] != $params['stay_date']) {
                            QCloudSmsService::create($params['accompany_mobile'])->sendChangeDateSms($row['stay_date'], $params['stay_date']);
                        }
                        // 通过申请转入订单
                        $this->model->changeOrder($params + $row->toArray(), $adminIds);
                    } else {
                        if ($row['stay_date'] != $params['stay_date']) {
                            exception(__('修改用户预计住院时间则必须为通过！'));
                        }
                    }
                    if ($params['status'] == 2 || $params['status'] == 3) {
                        if (!$params['reject_reason']) {
                            exception(__('请填写驳回原因！'));
                        }
                        $this->model->cancelOrder($params, $row['status'] === 0);
                    }
                    if ($params['room_info']) {
                        [$roomId, $roomTypeId] = explode(',', $params['room_info']);
                        $params['room_info_id'] = $roomId;
                        $params['room_type_id'] = $roomTypeId;
                    }
                    $row->allowField(true)->save($params);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['room_info'] = $row['room_info_id'] . ',' . $row['room_type_id'];
        $this->assign("row", $row);
        $this->assign("category", (new Category())->field('id,name,type,flag')->where(['pid' => 14])->select());

        $room = Db::name('pms_room_info')->where([
            'is_lock'     => 0,
            'state'       => 1,
            'room_status' => 0
        ])->select()->toArray();
        foreach ($room as &$item) {
            $item['room_info'] = $item['id'] . ',' . $item['room_type'];
        }
        $this->assign('roomList', $room);
        return $this->fetch();
    }
}
